package com.bootdo.api.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

public class JsonBeanSort {
	public static List<String> processBean(Object bean) {
		List<String> names = new ArrayList<String>();
		Class<?> clazz = bean.getClass().getSuperclass();
		Field[] supFields = new Field[] {};
		if (clazz != null) {
			supFields = clazz.getDeclaredFields();
			for (Field field : supFields) {
				try {
					names.add(field.getName());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		Field[] fields = bean.getClass().getDeclaredFields();
		for (Field field : fields) {
			try {
				names.add(field.getName());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return names;
	}

	/**
	 * 按对象顺序 排序
	 * 
	 * @param jsonObject
	 * @return
	 */
	public static JSONObject sort(JSONObject jsonObject, Object bean) {
		JSONObject newJsonObject = new JSONObject();
		List<String> names = processBean(bean);
		for (String str : names) {
			if (jsonObject.get(str) != null) {
				newJsonObject.put(str, jsonObject.get(str));
			}
		}
		return newJsonObject;
	}
}
